package zpe.relatorio.core;

import java.io.Serializable;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import zpe.relatorio.model.Extensao;
import zpe.relatorio.util.ResourceUtils;

/**
 * 
 * @author Evandir Rodrigo
 * @since 08/2010
 */
@Service("reportService")
public class ReportService implements Serializable {

    private static final long serialVersionUID = -4154822090445611695L;
    private static int parameter = 1;
    private @Resource FacadeReport facadeReport;

    public void execute(Map<String, Object> parameters, String report, Extensao formato) {

        FacesContext faces = FacesContext.getCurrentInstance();
        Map<String, Object> session = faces.getExternalContext().getSessionMap();

        byte[] data = null;

        if (formato.equals(Extensao.PDF)) {
            data = facadeReport.executePdf(report, parameters);
        } else if (formato.equals(Extensao.HTML)) {
            ServletContext ctx = ((HttpServletRequest) faces.getExternalContext().getRequest()).getSession(false).getServletContext();
            String dest = ctx.getRealPath("/");
            data = facadeReport.executeHtml(report, "report_" + parameter, dest, parameters);
        } else if (formato.equals(Extensao.XLS)) {
            data = facadeReport.executeXls(report, parameters);
        } else if (formato.equals(Extensao.ODT)) {
            data = facadeReport.executeODT(report, parameters);
        }

        long version =  new Date().getTime();
        session.put(String.valueOf(version), data);
        
        montaPopup(version);
    }

    private void montaPopup(long relarorio) {
        FacesContext faces = FacesContext.getCurrentInstance();
        ResourceUtils.addOutputStylesheetResource(faces, getScript(relarorio));
    }

    public FacadeReport getFacadeReport() {
        return facadeReport;
    }

    public void setFacadeReport(FacadeReport facadeReport) {
        this.facadeReport = facadeReport;
    }

    public String getScript(long relatorio) {
        
        final StringBuffer script = new StringBuffer();
        
		script.append(String.format("visualizarRelatorio(%d);", relatorio));
        
        return script.toString();
    }
}
